package com.hc.springsecurity;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler { //自定义登录成功后的处理器，转发或重定向由代码逻辑控制
    private String url;
    private boolean isRedirect;

    public MyAuthenticationSuccessHandler(String url, boolean isRedirect) {
        this.url = url;
        this.isRedirect = isRedirect;
    }

    /**
     * @param request        请求对象 request.getRequestDispatcher().forward()
     * @param response       响应对象 response.sendRedirect()
     * @param authentication 用户认证后的对象，其中包含用户名和权限集合。内容是自定义的UserDetailsService实现的方法值对象提供的
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("自定义认证成功处理逻辑执行……");
        if (isRedirect) {
            response.sendRedirect(url); //请求转发
        } else {
            request.getRequestDispatcher(url).forward(request, response);//重定向
        }
    }
}
